import os
import allure
import pytest
from selenium import webdriver
from Common.OperateionData import OperationData


@pytest.fixture(scope='function')
def get_driver():
    global driver
    driver = webdriver.Chrome()
    yield driver
    driver.quit()
    del driver


@pytest.fixture(params=OperationData(file_name='自动化测试数据.xlsx').get_data_to_list(), autouse=False)
def get_data(request):
    return request.param


# 用例失败后自动截图
@pytest.hookimpl(tryfirst=True, hookwrapper=True)
def pytest_runtest_makereport(item, call):
    """
    获取用例执行结果的钩子函数
    :param item:
    :param call:
    :return:
    """
    outcome = yield
    report = outcome.get_result()
    if report.when == "call" and report.failed:
        mode = "a" if os.path.exists("failures") else "w"
        with open("failures", mode)as f:
            if "tmpir" in item.fixturenames:
                extra = " (%s)" % item.funcargs["tmpdir"]
            else:
                extra = ""
                f.write(report.nodeid + extra + "\n")
            with allure.step('添加失败截图...'):
                allure.attach(driver.get_screenshot_as_png(), "失败截图", allure.attachment_type.PNG)
